﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Windows.Forms;
using System.IO;
using CTEM.Controllers.Global;

using CTEM.Models;
using System.Diagnostics;
using CTEM.Controllers.Global;

namespace CTEM.Controllers.DAO
{
    class CS_SubcontractorDAO
    {
        /// <summary>
        /// 
        /// </summary>
        public CS_SubcontractorDAO()
        {
            Transaction = null;
        }

        /// <summary>
        /// 
        /// </summary>
        private StackFrame _currentStackFrame;

        /// <summary>
        /// 
        /// </summary>
        public SqlTransaction Transaction { get; set; }

        /// <summary>
        /// 
        /// </summary>
        private SqlConnection _con;
        
        /// <summary>
        /// 
        /// </summary>
        SqlConnection Connection
        {
            get
            {
                if (_con == null)
                    _con = new SqlConnection(DatabaseInfo.ConnectionString);
                if (_con.State == ConnectionState.Closed)
                {
                    _con.Open();
                }
                return _con;
            }
            set
            {
                _con = value;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="subcon"></param>
        /// <returns></returns>
        public long CreateSubcontractor(CS_SubcontractorDTO subcon)
        {
            _currentStackFrame = new StackFrame();
            using (var cmd = new SqlCommand("[dbo].[CS_CreateSubcontractor]", Connection) { CommandType = CommandType.StoredProcedure })
            {
                if (Transaction != null)
                {
                    cmd.Transaction = Transaction;
                }
                try
                {
                    string[] parameternames = { "@SubcontractorName", 
                                                  "@SubcontractorAddress", 
                                                  "@PhoneNumber", 
                                                  "@NumberContract", 
                                                  "@TotalValueContract", 
                                                  "@IsActive",
                                                  "@IsDelete",
                                                  "@CreatedBy",
                                                  "@CreatedDate" };
                    object[] parametervalues = { subcon.SubcontractorName, 
                                                   subcon.SubcontractorAddress, 
                                                   subcon.PhoneNumber, 
                                                   subcon.NumberContract, 
                                                   subcon.TotalValueContract, 
                                                   subcon.IsActive,
                                                   subcon.IsDelete,
                                                   subcon.CreatedBy,
                                                   subcon.CreatedDate };
                    cmd.Parameters.AddRange(Global.Global.SetSqlParameter(parameternames, parametervalues));
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        if (reader.Read())
                            return Convert.ToInt64(reader[0]);
                    }
                    return 0;
                }
                catch (SqlException sql)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, sql.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return 0;
                }
                catch (Exception e)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, e.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return 0;
                }
                finally
                {
                    if (Transaction == null)
                        Connection.Close();
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="subcon"></param>
        /// <returns></returns>
        public bool UpdateSubcontractor(CS_SubcontractorDTO subcon)
        {
            _currentStackFrame = new StackFrame();
            using (var cmd = new SqlCommand("[dbo].[CS_UpdateSubcontractor]", Connection) { CommandType = CommandType.StoredProcedure })
            {
                if (Transaction != null)
                {
                    cmd.Transaction = Transaction;
                }
                try
                {
                    string[] parameternames = { "@SubcontractorID", 
                                                  "@SubcontractorName", 
                                                  "@SubcontractorAddress", 
                                                  "@PhoneNumber", 
                                                  "@NumberContract", 
                                                  "@TotalValueContract", 
                                                  "@IsActive",
                                                  "@IsDelete",
                                                  "@UpdatedBy",
                                                  "@LastUpdated" };
                    object[] parametervalues = { subcon.SubcontractorID, 
                                                   subcon.SubcontractorName, 
                                                   subcon.SubcontractorAddress, 
                                                   subcon.PhoneNumber, 
                                                   subcon.NumberContract, 
                                                   subcon.TotalValueContract, 
                                                   subcon.IsActive,
                                                   subcon.IsDelete,
                                                   subcon.UpdatedBy,
                                                   subcon.LastUpdated };
                    cmd.Parameters.AddRange(Global.Global.SetSqlParameter(parameternames, parametervalues));
                    cmd.ExecuteReader();
                    return true;
                }
                catch (SqlException sql)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, sql.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return false;
                }
                catch (Exception e)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, e.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return false;
                }
                finally
                {
                    if (Transaction == null)
                        Connection.Close();
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="subconID"></param>
        /// <returns></returns>
        public bool DeleteSubcontractor(long subconID)
        {
            _currentStackFrame = new StackFrame();
            using (var cmd = new SqlCommand("[dbo].[CS_DeleteSubcontractor]", Connection) { CommandType = CommandType.StoredProcedure })
            {
                if (Transaction != null)
                {
                    cmd.Transaction = Transaction;
                }
                try
                {
                    cmd.Parameters.Add(new SqlParameter("@SubcontractorID", subconID));
                    cmd.ExecuteNonQuery();
                    return true;
                }
                catch (SqlException sql)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, sql.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return false;
                }
                catch (Exception e)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, e.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return false;
                }
                finally
                {
                    if (Transaction == null)
                        Connection.Close();
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="subconID"></param>
        /// <returns></returns>
        public CS_SubcontractorDTO GetSubcontractorByID(long subconID)
        {
            _currentStackFrame = new StackFrame();
            using (var cmd = new SqlCommand("[dbo].[CS_GetSubcontractorByID]", Connection))
            {
                if (Transaction != null)
                {
                    cmd.Transaction = Transaction;
                }
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(new SqlParameter("@SubcontractorID", subconID));
                try
                {
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            CS_SubcontractorDTO consDTO = new CS_SubcontractorDTO
                            {
                                SubcontractorID = Convert.ToInt64(reader["SubcontractorID"]),
                                SubcontractorName = Convert.ToString(reader["SubcontractorName"]),
                                SubcontractorAddress = Convert.ToString(reader["SubcontractorAddress"]),
                                PhoneNumber = Convert.ToString(reader["PhoneNumber"]),
                                NumberContract = Convert.ToInt32(reader["NumberContract"]),
                                TotalValueContract = Convert.ToInt64(reader["TotalValueContract"]),
                                IsActive = Convert.ToBoolean(reader["IsActive"]),
                                IsDelete = Convert.ToBoolean(reader["IsDelete"]),
                                CreatedBy = Convert.ToString(reader["CreatedBy"]),
                                CreatedDate = Convert.ToDateTime(reader["CreatedDate"]),
                                UpdatedBy = Convert.ToString(reader["UpdatedBy"]),
                                LastUpdated = Convert.ToDateTime(reader["LastUpdated"])
                            };
                            return consDTO;
                        }
                        return null;
                    }
                }
                catch (SqlException sql)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, sql.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return null;
                }
                catch (Exception e)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, e.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return null;
                }
                finally
                {
                    if (Transaction == null)
                        Connection.Close();
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="isActive"></param> 
        /// <returns></returns>
        public List<CS_SubcontractorDTO> LoadAllSubcontractors(bool isActive)
        {
            _currentStackFrame = new StackFrame();
            using (var cmd = new SqlCommand("[dbo].[CS_GetAllSubcontractor]", Connection))
            {
                if (Transaction != null)
                {
                    cmd.Transaction = Transaction;
                }
                cmd.CommandType = CommandType.StoredProcedure;
                if (isActive)
                {
                    cmd.Parameters.Add(new SqlParameter("@IsActive", isActive));
                }
                else
                {
                    cmd.Parameters.Add(new SqlParameter("@IsActive", DBNull.Value));
                }
                try
                {
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        List<CS_SubcontractorDTO> listcons = new List<CS_SubcontractorDTO>();
                        while (reader.Read())
                        {
                            CS_SubcontractorDTO consDTO = new CS_SubcontractorDTO
                            {
                                SubcontractorID = Convert.ToInt64(reader["SubcontractorID"]),
                                SubcontractorName = Convert.ToString(reader["SubcontractorName"]),
                                SubcontractorAddress = Convert.ToString(reader["SubcontractorAddress"]),
                                PhoneNumber = Convert.ToString(reader["PhoneNumber"]),
                                NumberContract = Convert.ToInt32(reader["NumberContract"]),
                                TotalValueContract = Convert.ToInt64(reader["TotalValueContract"]),
                                IsActive = Convert.ToBoolean(reader["IsActive"]),
                                IsDelete = Convert.ToBoolean(reader["IsDelete"]),
                                CreatedBy = Convert.ToString(reader["CreatedBy"]),
                                CreatedDate = Convert.ToDateTime(reader["CreatedDate"]),
                                UpdatedBy = Convert.ToString(reader["UpdatedBy"]),
                                LastUpdated = Convert.ToDateTime(reader["LastUpdated"])
                            };
                            listcons.Add(consDTO);
                        }
                        return listcons;
                    }
                }
                catch (SqlException sql)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, sql.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return null;
                }
                catch (Exception e)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, e.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return null;
                }
                finally
                {
                    if (Transaction == null)
                        Connection.Close();
                }
            }
        }
        
    }
}
